<template>
  <view class="flex flex-col">
    <S1Header title="添加费用" :on-back="onBack" />

    <view class="border-f5f5f5 mt-20rpx flex justify-between border-b bg-white">
      <view class="tab-item" :class="{ 'tab-active': feeType === 'expense' }" @click="feeType = 'expense'">
        支出
      </view>
      <view class="tab-item" :class="{ 'tab-active': feeType === 'income' }" @click="feeType = 'income'">
        收入
      </view>
    </view>

    <view class="main-container">
      <view class="bg-[rgba(242,247,255,1)] p-20rpx">
        <!-- 金额输入 -->
        <view class="form-block">
          <text class="form-label">
            {{ feeType === 'expense' ? "支出" : "收入" }}金额
          </text>
          <view class="input-group">
            <input
              v-model="amount" class="h-60rpx flex-1 text-32rpx"
              :placeholder="`请输入${feeType === 'expense' ? '支出' : '收入'}金额`" type="number"
            >
            <div class="input-unit">
              元
            </div>
          </view>
        </view>

        <!-- 费用项目 -->
        <view class="form-block">
          <text class="form-label">
            {{ feeType === 'expense' ? "支出" : "收入" }}项目
          </text>
          <view class="input-group">
            <input
              class="h-60rpx flex-1 text-32rpx" :placeholder="`请选择${feeType === 'expense' ? '支出' : '收入'}项目`"
              disabled :value="selectedExpenseItem?.name || ''"
            >
            <div class="input-action-button" @click="toggleImportPopup('expense')">
              导入
            </div>
          </view>
        </view>

        <!-- 备注信息 -->
        <view class="form-block">
          <text class="form-label">
            备注信息
          </text>
          <view class="input-group">
            <input v-model="remark" class="flex-1 p-2px p-8px text-32rpx" placeholder="请输入备注信息">
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="mt-40rpx flex justify-center">
          <view class="h-90rpx w-100% flex items-center justify-center rounded-10rpx bg-[#43CF7C]" @click="submitFee">
            <text class="text-34rpx text-white font-bold">
              提交
            </text>
          </view>
        </view>
      </view>
    </view>

    <SearchFilterPopup
      :show="showImportPopup" :title="popupTitle" input-placeholder="搜索名称" :list="importItems"
      @update:show="showImportPopup = $event" @item-select="onItemSelect" @search="handleSearch"
    />
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import {
  addPiciZhichuData,
} from '@/api/order';
import {
  getAllFeiyongxiangData,
} from '@/api/statistics';
import * as S1Header from '@/components/S1Header.vue';
import * as SearchFilterPopup from '@/components/SearchFilterPopup.vue';

// 费用类型：expense 支出 / income 收入
const feeType = ref('expense');
// 金额
const amount = ref('');
// 备注
const remark = ref('');
// 导入相关
const showImportPopup = ref(false);
const importItems = ref<any[]>([]);
const popupType = ref<'expense'>('expense');
const selectedExpenseItem = ref<any>(null);
const isLoading = ref(false);
// 批次ID
const batchId = ref<string | number>('');

// 计算属性
const popupTitle = computed(() =>
  `${feeType.value === 'expense' ? '支出' : '收入'}项目搜索`,
);

// 返回
const onBack = (): void => {
  uni.navigateBack();
};

// 获取页面参数
onLoad((options: any) => {
  if (options.batchId) {
    batchId.value = options.batchId;
  }
});

// 显示导入弹窗
const toggleImportPopup = async (type: 'expense') => {
  if (isLoading.value) return;

  popupType.value = type;
  isLoading.value = true;

  try {
    const res = await getAllFeiyongxiangData({
      type: feeType.value === 'expense' ? 1 : 2,
      keywords: '',
      class: 'pici',
    });
    if (res.code === 200) {
      importItems.value = res.data.map((item: any) => ({
        name: item.name,
        id: item.id,
        phone: '', // 确保搜索过滤能正常工作
      }));
    }
    showImportPopup.value = true;
  }
  catch (error) {
    uni.showToast({
      title: '获取数据失败',
      icon: 'error',
    });
  }
  finally {
    isLoading.value = false;
  }
};

// 选择项目
const onItemSelect = (item: any) => {
  selectedExpenseItem.value = item;
  showImportPopup.value = false;
};

// 搜索处理
const handleSearch = async (keyword: string) => {
  if (isLoading.value) return;
  isLoading.value = true;

  try {
    const res = await getAllFeiyongxiangData({
      type: feeType.value === 'expense' ? 1 : 2,
      keywords: keyword,
    });
    if (res.code === 200) {
      importItems.value = res.data.map((item: any) => ({
        name: item.name,
        id: item.id,
        phone: '',
      }));
    }
  }
  catch (error) {
    uni.showToast({
      title: '搜索失败',
      icon: 'error',
    });
  }
  finally {
    isLoading.value = false;
  }
};

// 提交费用
const submitFee = async () => {
  if (isLoading.value) return;

  // 表单验证
  if (!selectedExpenseItem.value) {
    uni.showToast({
      title: '请选择费用项目',
      icon: 'none',
    });
    return;
  }

  if (!amount.value) {
    uni.showToast({
      title: '请输入金额',
      icon: 'none',
    });
    return;
  }

  if (!batchId.value) {
    uni.showToast({
      title: '批次ID不能为空',
      icon: 'none',
    });
    return;
  }

  try {
    isLoading.value = true;

    const res = await addPiciZhichuData({
      money: amount.value,
      name: selectedExpenseItem.value.name,
      name_id: selectedExpenseItem.value.id,
      notes: remark.value,
      pay_type: feeType.value === 'expense' ? 1 : 2, // 根据费用类型设置支付类型
      pici_id: typeof batchId.value === 'string' ? Number.parseInt(batchId.value) : batchId.value,
      type: feeType.value === 'expense' ? '1' : '2', // 转为字符串类型
    });

    if (res.code === 200) {
      uni.showToast({
        title: '提交成功',
        icon: 'success',
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
    else {
      uni.showToast({
        title: res.msg || '提交失败',
        icon: 'error',
      });
    }
  }
  catch (error) {
    uni.showToast({
      title: '提交失败',
      icon: 'error',
    });
  }
  finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #666;
  padding: 20rpx;
  border-radius: 5rpx;
  transition: all 0.3s;
}

.tab-active {
  color: white;
  background-color: #43cf7c;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-block {
  margin-bottom: 20rpx;
  border-bottom: 1px solid #eee;
  padding: 20rpx;
  background-color: white;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: black;
  font-size: 17px;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.input-group {
  display: flex;
  align-items: center;
  background-color: rgba(242, 247, 255, 1);
  padding-left: 12px;
  border-radius: 5px;
}

.input-unit,
.input-action-button {
  border-radius: 0 7.43px 7.43px 0;
  background-color: rgba(67, 207, 124, 1);
  border: 1px solid rgba(229, 229, 229, 1);
  color: white;
  font-size: 32rpx;
  width: 120rpx;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  font-weight: bold;
}
</style>
